<?php
//namespace student\controller\welcome;
defined('BASEPATH') OR exit('No direct script access allowed');

class Gopay extends CI_Controller {


	public function __construct()
	{
		parent::__construct();
		//$this->load->model('');
		$this->load->helper('url_helper');
		$this->load->model('getdatahub');
		$this->load->model('getorder');
		$this->load->library('alipayservice');
		$this->load->library('configservice');
		$this->load->model('getuser');
		//$this->load->library('captcha');
		session_start();
	}

    /**
    *  支付页面主函数
    */
	public function index()
	{
		$id = $_REQUEST['param']?$_REQUEST['param']:1;
		$num = $_REQUEST['number']?$_REQUEST['number']:1;
		$res = $this->getdatahub->getdetail($id);
		$res_data = array("data"=>$res,"num"=>$num);
		$this->load->view('home/payment',$res_data);
	}


    /**
    *  选择付款方式以及生成订单
    **/
	public function chooseType()
	{
		$type = @$_REQUEST['paytype'];
		$ordername = @$_REQUEST['ordername'];
		$dataId = @$_REQUEST['dataId'];
		$goodsNum = @$_REQUEST['goodsNum'];
		$unitPrice = @$_REQUEST['unitPrice'];
		$buyer = @$_SESSION['user_id']?@$_SESSION['user_id']:1;
		$discount = "不打折";
		$res = $this->getorder->setOrderId($dataId); //生成 订单号=购买者id+时间+拥有者id
        $orderId = $res['orderId'];
        $owner_id = $res['owner_id'];

        $pay_type = $type == "alipay"?"1":($type == "weixinpay"?"2":($type == "unionpay"?"4":"3"));

		$orderArray = array('order_name'=>$ordername,'order_id'=>$orderId,'unit_price'=>$unitPrice,
							'order_num'=>$goodsNum,'total_price'=>$unitPrice*$goodsNum,'discount'=>$discount,
							'owner_id'=>$res['owner_id'],'buyer_id'=>$buyer,'buy_time'=>date("Y-m-d H:i:s"),
							'last_time'=>date('Y-m-d H:i:s'),'pay_type'=>$pay_type
	                );
		$res = $this->getorder->insertData($orderArray);
 
		if($res){
			switch ($type) {
				case 'alipay':
					print $this->alipay($orderArray);
					break;
				
				case 'weixinpay':
				    $this->weixinpay($orderArray);
				    break;

				case 'unionpay':
					$this->unionpay($orderArray);
					break;

				default:
					$res = $this->accountpay($orderArray);
					if($res == 1){
						print "余额不足，请充值";
					} else if( $res == 2){
						print "余额支付成功";
					} else {
						print "余额支付失败";
					}
					break;
			}
		} else {
			print json_encode(array('code'=>0,'desc'=>'订单生成失败'));
		}
	}

    /**
	*  支付宝支付主函数
    **/
	public function alipay($payarray)
	{
		$appid = $this->configservice->getAppid();			//https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
		$returnUrl = '<?=base_url()?>index.php/home/gopay/alireturn';     //付款成功后的同步回调地址
		$notifyUrl = '<?=base_url()?>index.php/home/gopay/alinotify';     //付款成功后的异步回调地址

		$outTradeNo = $payarray['order_id'];     //你自己的商品订单号，不能重复
		$payAmount = $payarray['total_price'];          //付款金额，单位:元
		$orderName = $payarray['order_name'];    //订单标题k

		$signType = 'RSA2';			//签名算法类型，支持RSA2和RSA，推荐使用RSA2	
		$rsaPrivateKey = $this->configservice->getrsaPrivateKey();//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
		/*** 配置结束 ***/
	

		$this->alipayservice->setAppid($appid);
		$this->alipayservice->setReturnUrl($returnUrl);
		$this->alipayservice->setNotifyUrl($notifyUrl);
		$this->alipayservice->setRsaPrivateKey($rsaPrivateKey);
		$this->alipayservice->setTotalFee($payAmount);
		$this->alipayservice->setOutTradeNo($outTradeNo);
		$this->alipayservice->setOrderName($orderName);
		$sHtml = $this->alipayservice->doPay();
		//echo $sHtml;
		return $sHtml;
	}


	/**
	*  微信支付主函数
	*/
	public function weixinpay($payarray)
	{

	}


	/**
	*  银联支付主函数
	*/

	public function unionpay($payarray)
	{

	}


	/**
	* 账户余额支付
	**/
    public function accountpay($payarray)
    {
    	$order_price = $payarray['total_price'];
    	$user_id = $_SESSION['user_id'];
    	$balance = $this->getuser->getbalance($user_id);
    	if($order_price > $balance){
    		return 1; //表示账户余额不足
    	}
    	$res = $this->getorder->goPay($payarray['order_id'],"accountpay"); //更新orderinfo信息表

    	$new_balance = $balance - $order_price;

    	$res2 = $this->getuser->updateBalance($user_id,$new_balance,$payarray['order_id']); //更新账户余额信息表

    	if($res && $res2){
    		return 2; //表示成功
    	} else {
    		return 3; //表示支付失败
    	}
    }


    /**
    * 订单详单跳转支付
    **/
    public function detailPay()
    {
    	$orderId = $_REQUEST['orderId'];
    	$type = @$_REQUEST['type']? @$_REQUEST['type']:"alipay";
    	$res = $this->getorder->getOrderByorderid($orderId);
    	$orderArray = array("order_id"=>$orderId,"order_name"=>$res['order_name'],"total_price"=>$res['total_price']);
        //默认使用alipay支付
        switch ($type) {
			case 'alipay':
				print json_encode(array('code'=>1,"data"=>$this->alipay($orderArray)));
				break;
			
			case 'weixinpay':
			    $this->weixinpay($orderArray);
			    break;

			case 'unionpay':
				$this->unionpay($orderArray);
				break;

			default:
				$res = $this->accountpay($orderArray);
				if($res == 2){
					print json_encode(array("code"=>1,"desc"=>"余额支付成功"));
				} elseif($res ==1) {
					print json_encode(array("code"=>2,"desc"=>"余额不足，请充值"));
				} else {
					print json_encode(array("code"=>2,"desc"=>"余额支付失败"));
				}
				break;
		}
    }
}
